import { getRdsUrl, rdsRequestAsync } from './rdsServices';

const getGstatus = async () => {
    const chgStatusLiftCycleRange = {
        ['']: [],
        ['0']: [],
        ['1']: ['2', '3', '7'],
        ['2']: ['3', '7'],
        ['3']: ['4', '5', '7'],
        ['4']: ['3', '4', '5', '7'],
        ['5']: ['3', '4', '5', '7'],
        ['7']: ['8', '3', '9', '5'],
        ['8']: ['3', '9']
    };

    const gstatus = [];
    const gstatusCtrl = [];
    const gstatusItems = [];
    const gstatusAllItems = [];
    let loaded = false;

    const rdsUrl = getRdsUrl();

    const result = await rdsRequestAsync(rdsUrl.bcApi, 'Rds公共服务', 'GetAllGstatuInfo', '');
    if (!result.HasException) {
        gstatus.splice(0, gstatus.length, ...result.ObjectData.ds);
        gstatusCtrl.splice(0, gstatusCtrl.length, ...result.ObjectData.ds1);
        gstatusItems.splice(0, gstatusItems.length, ...gstatus
        .filter(f => f.c_lift_cycle !== '0')
        .map(item => ({ value: item.c_id, title: item.c_name })));
        gstatusAllItems.splice(0, gstatusAllItems.length, ...gstatus
        .map(item => ({ value: item.c_id, title: item.c_name })));
    }

    function getGstatusName(id) {
        const item = gstatusItems.find(g => g.value === id);
        return item ? item.title : null;
    }

    function getGstatusItems(liftSycle, excludes) {
        return gstatus
        .filter(f => !liftSycle || liftSycle.includes(f.c_lift_cycle))
        .filter(f => !excludes || !excludes.includes(f.c_lift_cycle))
        .map(item => ({ value: item.c_id, title: item.c_name }));
    }

    function getNextGstatusItems(status, excludesLiftCycle) {
        const nextStatus = gstatusCtrl
        .filter(f => f.c_id === status)
        .map(f => f.c_chg_id);

        return gstatus
        .filter(f => nextStatus.includes(f.c_id))
        .filter(f => !excludesLiftCycle || !excludesLiftCycle.includes(f.c_lift_cycle))
        .map(item => ({ value: item.c_id, title: item.c_name }));
    }

    function getLiftCycle(id) {
        const status = gstatus.find(f => f.c_id === id);
        return status ? status.c_lift_cycle : '';
    }

    function getStatusId(liftSycle) {
        const status = gstatus.find(f => f.c_lift_cycle === liftSycle);
        return status ? status.c_id : '';
    }

    function getStatusCtrl(id, chgId, nextId) {
        return gstatusCtrl.filter(f =>
          (!id || f.c_id === id)
          && (!chgId || f.c_chg_id === chgId)
          && (!nextId || f.c_next_id === nextId)
        );
    }

    return {
        gstatusItems,
        gstatus,
        gstatusAllItems,
        getGstatusName,
        getLiftCycle,
        getStatusId,
        getGstatusItems,
        getNextGstatusItems,
        getStatusCtrl
    };
};



export { getGstatus }
